<?php
/**
 ** 
 **/
class TalkRoom 
{
    public $server;
    public $list;
    public $redis;

    function __construct()
    {
        $this->server = new swoole_websocket_server("0.0.0.0", 9501);
        $server = $this->server;
        $this->redis = new Redis();
        //连接
        $this->redis->connect('127.0.0.1', 6379);
        // 设置配置
        $server->set(
            array(
                'daemonize' => false,      // 是否是守护进程
                'max_request' => 10000,    // 最大连接数量
                'dispatch_mode' => 2,
                'debug_mode'=> 1,
                // 心跳检测的设置，自动踢掉掉线的fd
                'heartbeat_check_interval' => 5,
                'heartbeat_idle_time' => 600,
            )
        );
        //连接事件
        $server->on('open',function($server,$request){
            //添加fd
            $this->list[$request->fd] = $request->fd;
            echo $request->fd.' is in talkroom \n';
            $this->server->push($request->fd,'welcome to the talkroom');

            // swoole_timer_tick(2000, function ($timer_id) {
            //     // echo "tick-2000ms\n";
            //     $server->push($request->fd, 'ok');
            // });
            // $server->addtimer(1000);

        });

        $server->on('message',function($server,$request){

            // foreach ($this->list as $key => $value) {
            //     $server->addtimer(1000);
            //     swoole_timer_tick(1000, function ($value) {
            //         $server->push($value, 'ok');
            //     });
            // }

            // echo $request->data.'\n';
            $data = json_decode($request->data,1);
            // var_dump($data);
            // echo '\n';
            // //设置房间
            if($data['type']==1){
                $room = $data['msg'];
                $this->redis->set($request->fd,$room);
                // $i = 0;
                // $server->tick(1000,function() use ($server,$request) {
                    // $i++;
                    $server->push($request->fd,'1');
                // });
            }
            // //设置发送房间信息
            // if($data['type']==2){
            //     $msg = $data['msg'];
            //     $room = $this->redis->get($request->fd);
            //     //判断是否同一房间，发送信息
                
            //         $all_room = $this->redis->get($value);
            //         if($room==$all_room){
                        
            //         }
            // }
        });
        $server->on('close',function($server,$request){
            echo $request.' is close room \n';
            $server->close($request);   // 销毁fd链接信息
        });
        //启动swoole服务
        $server->start();
    }

    function onTimer($server,$msg){
        $server->push(0, 'ok');
    }
}
$talk = new TalkRoom();